//
//  PersonalViewController.m
//  ChatForHot
//
//  Created by FLY on 2018/10/9.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "PersonalViewController.h"
#import "BaseTableView.h"
#import "PersonalViewModel.h"
#import "PersonalCell.h"
#import "PersonalHeadView.h"
#import "HOTCHATClipViewController.h"
#import "PersonalSettingViewController.h"
#import "PersonalProfileViewController.h"
#import "PersonalIdentificationViewController.h"
#import "PersonalUserPhotoViewController.h"
#import "PersonalVipViewController.h"
#import "HCHelper.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

@interface PersonalViewController ()<UITableViewDelegate, UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate,ClipViewControllerDelegate>

@property (nonatomic, strong) BaseTableView *HOTCHATtableView;
@property (nonatomic, strong) PersonalViewModel *viewModel;
@property (nonatomic, strong) PersonalHeadView *HOTCHATheadView;
@end

@implementation PersonalViewController

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    self.viewModel = [[PersonalViewModel alloc] init];
}

- (void)HOTCHATInsertSubViews {
    
    self.HOTCHATtableView = [[BaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.HOTCHATtableView.delegate = self;
    self.HOTCHATtableView.dataSource = self;
    [self.HOTCHATtableView registerClass:[PersonalCell class] forCellReuseIdentifier:@"PersonalCell"];
    self.HOTCHATheadView = [[PersonalHeadView alloc] initWithFrame:CGRectMake(0, 0, HOTCHATUIWIDTH, 373.0)];
    [self.HOTCHATheadView HOTCHATbind];
    self.HOTCHATtableView.tableHeaderView = self.HOTCHATheadView;
    [self.view addSubview:self.HOTCHATtableView];
}

- (void)HOTCHATsetNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated {
    [super HOTCHATsetNavigationItemsIsInEditMode:isInEditMode animated:animated];
    self.title = NSLocalizedString(@"person11", nil);
    UIButton *settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingButton setImage:[UIImage imageNamed:@"personal_setting_n"]forState:UIControlStateNormal];
    [settingButton setImage:[UIImage imageNamed:@"personal_setting_h"]forState:UIControlStateHighlighted];
    [settingButton sizeToFit];
    UIBarButtonItem *settingButtonItem = [[UIBarButtonItem alloc] initWithCustomView:settingButton];
    self.navigationItem.rightBarButtonItem = settingButtonItem;
    @weakify(self)
    [[settingButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self)
        PersonalSettingViewController *vc = [[PersonalSettingViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.HOTCHATtableView.frame = CGRectMake(0, 0,
                                             kScreenWidth,
                                             kScreenHeight - self.tabBarSpacingInViewCoordinator - (iPhoneX ? 44 : 20) - 44);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    @weakify(self)
    [self.HOTCHATheadView.avatarDidSelected subscribeNext:^(id x) {
        @strongify(self)
        [self HOTCHATAvatarClick];
    }];
    
    [self.HOTCHATheadView.vipDidSelected subscribeNext:^(id x) {
        @strongify(self)
        PersonalVipViewController *vc = [[PersonalVipViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.viewModel.profileDidSelectSubject subscribeNext:^(id x) {
        @strongify(self)
        PersonalProfileViewController *vc = [[PersonalProfileViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }];
    
    [self.viewModel.photoVaultDidSelectSubject subscribeNext:^(id x) {
        @strongify(self)
        PersonalUserPhotoViewController *vc = [[PersonalUserPhotoViewController alloc] initWithPhotoType:PrivatePhoto];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.viewModel.albumDidSelectSubject subscribeNext:^(id x) {
        @strongify(self)
        PersonalUserPhotoViewController *vc = [[PersonalUserPhotoViewController alloc] initWithPhotoType:CommonPhoto];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.viewModel.identificationDidSelectSubject subscribeNext:^(id x) {
        @strongify(self)
        PersonalIdentificationViewController *vc = [[PersonalIdentificationViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.viewModel.avatarDidChangeSubject subscribeNext:^(id x) {
        @strongify(self)
        [self.HOTCHATheadView HOTCHATbind];
        [self HOTCHATstopLoading];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.HOTCHATheadView HOTCHATbind];
}

#pragma mark - SelectedPhotoActions

- (void)HOTCHATAvatarClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:NSLocalizedString(@"alert2", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATOpenCamera];
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:NSLocalizedString(NSLocalizedString(@"alert3", nil), nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATPopenPhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(NSLocalizedString(@"alert1", nil), nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)HOTCHATOpenCamera {
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    [imagePicker setDelegate:self];
    
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"access2", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"clip3", nil) otherButtonTitles:nil, nil];
        alertView.tag = 100;
        [alertView show];
    }else {
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)HOTCHATPopenPhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    @weakify(self)
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            if ( status == PHAuthorizationStatusAuthorized) {
                [self presentViewController:picker animated:YES completion:nil];
            }else if (status == PHAuthorizationStatusDenied) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"access1", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"clip3", nil) otherButtonTitles:nil, nil];
                alertView.tag = 100;
                [alertView show];
            }
        });
    }];
}

#pragma mark - <UIImagePickerControllerDelegate>

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    portraitImg = [[HCHelper sharedInstance] HOTCHATimageCompressToMaxSize:portraitImg];
    // 裁剪
    HOTCHATClipViewController *clipView = [[HOTCHATClipViewController alloc] initWithImage:portraitImg];
    clipView.delegate = self;
    clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
    clipView.radius = 150;   //设置 裁剪框的半径  默认120
    clipView.scaleRation = 3;//图片缩放的最大倍数
    clipView.isCamera = (picker.sourceType == UIImagePickerControllerSourceTypeCamera);
    [picker pushViewController:clipView animated:YES];
}

#pragma mark - ClipViewControllerDelegate

-(void)ClipViewController:(HOTCHATClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage{
    @weakify(self)
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self)
        [self HOTCHATstartLoading];
        [self.viewModel HOTCHATuploadActionImg:editImage];
        [clipViewController dismissViewControllerAnimated:YES completion:^{
        }];
    });
}

#pragma mark - <UITableViewDataSource,UITableViewDelegate>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.cellDataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonalCellModel *row = [self.viewModel.cellDataSource objectOrNilAtIndex:indexPath.row];
    return row.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonalCellModel *cellModel = [self.viewModel.cellDataSource objectOrNilAtIndex:indexPath.row];
    PersonalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonalCell"];
    [cell HOTCHATbind:cellModel];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonalCellModel *cellModel = [self.viewModel.cellDataSource objectOrNilAtIndex:indexPath.row];
    if (cellModel.handler) { cellModel.handler(); }
    
}


@end
